package com.app.shop.activitys;

import android.content.ContentValues;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.app.shop.R;
import com.app.shop.adapters.ShopCarAdapter;
import com.app.shop.beans.GoodsBean;
import com.app.shop.beans.OrderBean;
import com.app.shop.beans.ShopCarBean;
import com.app.library.base.BaseActivity;
import com.app.library.beans.EventMessage;
import com.app.library.utils.DialogUtil;
import com.app.library.utils.StringUtil;
import com.app.library.utils.TimeUtil;
import com.app.library.utils.ToastUtil;
import com.app.library.utils.UserManager;
import com.app.library.widgts.CustomDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

public class  ShopCarActivity extends BaseActivity implements View.OnClickListener {


   private TextView tvTitle;

    private  RecyclerView recy;

    private TextView tvPrice;

    private LinearLayout llBottom;
   private   ImageView imgvreturn;
    private   TextView tvok;
    private List<ShopCarBean> list = new ArrayList<>();
    private ShopCarAdapter adapter;

    private CustomDialog customDialog;

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_car);
        tvTitle= (TextView) findViewById(R.id.tv_title);
        recy= (RecyclerView) findViewById(R.id.recy);
        tvPrice= (TextView) findViewById(R.id.tv_price);
        llBottom= (LinearLayout) findViewById(R.id.ll_bottom);
       imgvreturn= (ImageView) findViewById(R.id.imgv_return);
        tvok= (TextView) findViewById(R.id.tv_ok);
        imgvreturn.setOnClickListener(this::onClick);
        tvok.setOnClickListener(this::onClick);
        tvTitle.setText("购物车");
        initData();
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imgv_return:
                onBackPressed();
                break;
            case R.id.tv_ok:
                comfirm();
                break;
        }
    }

    private void initData() {
        list.clear();
        List<ShopCarBean> list_all = DataSupport.findAll(ShopCarBean.class);
        List<GoodsBean> list_goods = DataSupport.findAll(GoodsBean.class);
        for (int i = 0; i < list_all.size(); i++) {
            if (list_all.get(i).getCreate_user_id().equals(UserManager.getUserId(this))) {
                list.add(list_all.get(i));
            }
        }
        if (list.size() == 0) {
            llBottom.setVisibility(View.GONE);
        } else {
            llBottom.setVisibility(View.VISIBLE);
        }
        adapter = new ShopCarAdapter(R.layout.item_goods_list, list);
        adapter.setEmptyView(LayoutInflater.from(this).inflate(R.layout.view_list_empty, null));
        recy.setLayoutManager(new LinearLayoutManager(this));
        recy.setAdapter(adapter);

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                for (int i = 0; i < list_goods.size(); i++) {
                    if (list_goods.get(i).getGoods_id().equals(list.get(position).getGoods_id())) {
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("bean", list_goods.get(i));
                        showActivity(ShopCarActivity.this, GoodsDetailActivity.class, bundle);
                    }
                }
            }
        });

        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                del(position);
            }
        });

        tvPrice.setText("总价：" + getTotal());
    }

    public int getTotal() {
        int total = 0;
        for (int i = 0; i < list.size(); i++) {
            String price = list.get(i).getGoods_price();
            if (StringUtil.isNumeric(price)) {
                int p = Integer.parseInt(price);
                total += p;
            }
        }
        return total;

    }


    private void del(int position) {
        customDialog = DialogUtil.showDialog(this, customDialog, 2, "确认", "删除该商品", "取消", "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                DataSupport.deleteAll(ShopCarBean.class, "s_id=?", list.get(position).getS_id());
                list.remove(position);
                adapter.notifyDataSetChanged();

            }
        });

        if (customDialog != null && !customDialog.isShowing()) {
            customDialog.show();
        }

        customDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                customDialog = null;
            }
        });
    }



    private void comfirm() {
        if (list.size() == 0) {
            ToastUtil.showToast(this, "暂无商品");
            return;
        } else {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < list.size(); i++) {
                sb.append(list.get(i).getGoods_id() + ",");

                ContentValues values = new ContentValues();
                values.put("status", 1);
                DataSupport.updateAll(GoodsBean.class, values, "goods_id=?", list.get(i).getGoods_id());
                EventBus.getDefault().post(new EventMessage(EventMessage.REFRESH));
            }
            OrderBean orderBean = new OrderBean();
            orderBean.setOrder_id(System.currentTimeMillis() + "");
            orderBean.setGoods_ids(sb.substring(0, sb.length() - 1));
            orderBean.setUser_id(UserManager.getUserId(this));
            orderBean.setPrice(getTotal() + "");
            orderBean.setTime(TimeUtil.getTodayData("yyyy-MM-dd HH:mm:ss"));
            orderBean.save();
            for (int i = 0; i < list.size(); i++) {
                DataSupport.deleteAll(ShopCarBean.class, "s_id=?", list.get(i).getS_id());
            }


            list.clear();
            adapter.notifyDataSetChanged();
            llBottom.setVisibility(View.GONE);
            ToastUtil.showToast(ShopCarActivity.this, "支付成功");
            Bundle bundle = new Bundle();
            bundle.putSerializable("bean", orderBean);
            showActivity(this, OrderDetailActivity.class, bundle);
        }
    }

    @Override
    public void onEvent(EventMessage msg) {
        super.onEvent(msg);
        if (msg.getMessageType() == EventMessage.REFRESH) {
            initData();
        }
    }


}
